const express = require('express');
const router = express.Router();
const pool = require('../db');
const authMiddleware = require('../middleware/auth');
const { createLog } = require('../log');

// GET /api/devices
// If page & limit provided returns { devices: [...], total }
// Otherwise returns { devices: [...] }
router.get('/devices', authMiddleware, async (req, res) => {
  try {
    // log page open
    createLog(req, { message: '打开设备列表', tp: 'view' });

    const page = req.query.page ? Math.max(1, parseInt(req.query.page, 10) || 1) : null;
    const limit = req.query.limit ? Math.max(1, parseInt(req.query.limit, 10) || 10) : null;
    const offset = page && limit ? (page - 1) * limit : null;

    const allowedSorts = {
      device_name: 'd.device_name',
      device_code: 'd.device_code',
      remark: 'd.remark',
      hospital_name: 'h.hos_name',
      id: 'd.id'
    };
    const sortBy = typeof req.query.sort_by === 'string' ? req.query.sort_by : null;
    let sortOrder = typeof req.query.sort_order === 'string' ? req.query.sort_order.toLowerCase() : null;
    if (sortOrder !== 'asc' && sortOrder !== 'desc') sortOrder = null;

    let orderClause = 'd.id DESC';
    if (sortBy && allowedSorts[sortBy]) {
      orderClause = `${allowedSorts[sortBy]} ${sortOrder === 'asc' ? 'ASC' : 'DESC'}`;
    }

    let sql = `SELECT d.id, d.device_name, d.device_code, d.remark, d.hospital, h.hos_name AS hospital_name FROM atb_device d LEFT JOIN atb_hospital h ON d.hospital = h.id ORDER BY ${orderClause}`;

    if (page && limit) {
      sql += ' LIMIT ? OFFSET ?';
      const [rows] = await pool.query(sql, [limit, offset]);
      const [countRows] = await pool.query('SELECT COUNT(*) AS total FROM atb_device');
      const total = (countRows && countRows[0] && countRows[0].total) ? countRows[0].total : 0;
      return res.json({ devices: rows, total });
    } else {
      const [rows] = await pool.query(sql);
      return res.json({ devices: rows });
    }
  } catch (err) {
    console.error('Failed to fetch devices:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// POST /api/devices
router.post('/devices', authMiddleware, async (req, res) => {
  try {
    const { device_name, device_code, remark, hospital } = req.body;
    if (!device_name) return res.status(400).json({ message: 'device_name required' });

    const [result] = await pool.query('INSERT INTO atb_device (device_name, device_code, remark, hospital) VALUES (?, ?, ?, ?)', [device_name, device_code || null, remark || null, hospital || null]);
    const insertId = result.insertId;
    const [rows] = await pool.query('SELECT d.id, d.device_name, d.device_code, d.remark, d.hospital, h.hos_name AS hospital_name FROM atb_device d LEFT JOIN atb_hospital h ON d.hospital = h.id WHERE d.id = ?', [insertId]);

    // log creation
    createLog(req, { message: `新增设备 ${device_name}`, tp: 'create', obj_json: JSON.stringify(rows[0] || { id: insertId, device_name }) });

    res.status(201).json({ device: rows[0] });
  } catch (err) {
    console.error('Failed to create device:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// PUT /api/devices/:id
router.put('/devices/:id', authMiddleware, async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    if (isNaN(id)) return res.status(400).json({ message: 'Invalid device id' });

    const { device_name, device_code, remark, hospital } = req.body;
    const fields = [];
    const params = [];

    if (typeof device_name !== 'undefined') { fields.push('device_name = ?'); params.push(device_name); }
    if (typeof device_code !== 'undefined') { fields.push('device_code = ?'); params.push(device_code); }
    if (typeof remark !== 'undefined') { fields.push('remark = ?'); params.push(remark); }
    if (typeof hospital !== 'undefined') { fields.push('hospital = ?'); params.push(hospital); }

    if (fields.length === 0) return res.status(400).json({ message: 'No fields to update' });

    params.push(id);
    const sql = `UPDATE atb_device SET ${fields.join(', ')} WHERE id = ?`;
    await pool.query(sql, params);

    const [rows] = await pool.query('SELECT d.id, d.device_name, d.device_code, d.remark, d.hospital, h.hos_name AS hospital_name FROM atb_device d LEFT JOIN atb_hospital h ON d.hospital = h.id WHERE d.id = ?', [id]);

    // log update
    createLog(req, { message: `编辑设备 id=${id}`, tp: 'update', obj_json: JSON.stringify(rows[0] || { id }) });

    res.json({ device: rows[0] });
  } catch (err) {
    console.error('Failed to update device:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// DELETE /api/devices/:id
router.delete('/devices/:id', authMiddleware, async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    if (isNaN(id)) return res.status(400).json({ message: 'Invalid device id' });

    await pool.query('DELETE FROM atb_device WHERE id = ?', [id]);

    // log delete
    createLog(req, { message: `删除设备 id=${id}`, tp: 'delete', obj_json: JSON.stringify({ id }) });

    res.json({ ok: true });
  } catch (err) {
    console.error('Failed to delete device:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;
